package com.yugao.fintech.antelope.statistic.handler;

import com.yugao.fintech.antelope.statistic.api.constant.StatisticCons;
import com.yugao.fintech.antelope.statistic.api.model.mq.StatisticMQ;
import com.yugao.fintech.framework.assistant.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 统计处理器
 */
@Slf4j
public abstract class AbstractStatisticHandler {
    private static final Map<String, AbstractStatisticHandler> handlerMap = new ConcurrentHashMap<>();

    @PostConstruct
    public void initStatisticHandler() {
        if (StringUtils.isEmpty(type())) {
           log.warn("statisticHandler [{}] type is null", this.getClass().getSimpleName());
           return;
        }
        handlerMap.put(type(), this);
    }
    /**
     * 统计类型
     * @return {@link StatisticCons.Type}
     */
    public abstract String type();

    /**
     * 处理统计消息
     * @param req 消息
     */
    public abstract void process(StatisticMQ.Payload req);

    /**
     * 用于执行任务, 比如统计访问量, 需要先经过mq, 然后由 {@link #process(StatisticMQ.Payload)} 处理存入到缓存中,
     * 定时任务每晚22:50分, 开始将缓存中的数据取出并清空, 然后将其落库
     */
    public abstract void execTask(Long tenantId);

    public static AbstractStatisticHandler getHandler(StatisticMQ.Payload req) {
        return handlerMap.get(req.getType());
    }

    /**
     *
     * @see StatisticCons.Type
     */
    public static AbstractStatisticHandler getHandler(String type) {
        return handlerMap.get(type);
    }
}
